package com.cheng.web.action;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.Map;

import javax.ws.rs.core.MediaType;

import org.apache.commons.io.FileUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.cheng.bos.actionUtils.ActionUtils;
import com.cheng.domain.page.PageBean;
import com.cheng.domain.takedelivery.Promotion;
import com.opensymphony.xwork2.ActionContext;

import freemarker.template.Configuration;
import freemarker.template.Template;

@Namespace("/promotion")
@ParentPackage("json-default")
@Controller
@Scope("prototype")
public class PromoationAction extends ActionUtils<Promotion>{
	
	private String address ="http://localhost:8080/bos_management/service/promotionService";

	@Action(value="promotion_pagequery",results={@Result(type="json")})
	public String pageQueryPromoation(){
		PageBean pageBean = WebClient.create(address+"/allpromotion?page="+page+"&rows="+rows).accept(MediaType.APPLICATION_JSON).get(PageBean.class);
		ActionContext.getContext().getValueStack().push(pageBean);
		return SUCCESS;
	}
	
	@Action(value="promotion_message")
	public String findPromoation(){
		try {
			String htmlPath = ServletActionContext.getServletContext().getRealPath("/freemarker");
			File htmlFile = new File(htmlPath+"/"+model.getId()+".html");
			if (!htmlFile.exists()) {
				Configuration configuration = new Configuration(Configuration.VERSION_2_3_22);
				configuration.setDirectoryForTemplateLoading(new File(ServletActionContext.getServletContext().getRealPath("/WEB-INF/freemarker_templates")));
				Template template = configuration.getTemplate("promotion_detail.ftl");
				Promotion promotion = WebClient.create(address).path("/promotionmessage/"+model.getId()).accept(MediaType.APPLICATION_JSON).get(Promotion.class);
				Map<String, Object> templatemap = new HashMap<String, Object>();
				templatemap.put("promotion", promotion);
				template.process(templatemap,new OutputStreamWriter(new FileOutputStream(htmlFile),"utf-8"));
			}
			ServletActionContext.getResponse().setContentType("text/html;charset=utf-8");
			FileUtils.copyFile(htmlFile, ServletActionContext.getResponse().getOutputStream());
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return NONE;
	}
	
}
